package net.thetabx.ftdba.activities;

import net.thetabx.ftdba.GlobalData;
import net.thetabx.ftdba.R;
import net.thetabx.ftdba.RStatus;
import net.thetabx.ftdba.http.HttpData;
import net.thetabx.ftdba.http.HttpManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;

public class ConnectorActivity extends Activity {
    
    private Button btnConnect = null;
    private Button btnCancel = null;
    
    private HttpManager http;
    private RStatus connectorStatus;
    private SharedPreferences settings;
    private Resources res;
    
    private EditText editNick;
    private EditText editPass;
    private CheckBox chkSecure;
    private CheckBox chkRemember;
    private CheckBox chkInvis;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.connector);
        res = getResources();
        
        http = GlobalData.getHttpManager();
        
        settings = getSharedPreferences("LoginCreds", MODE_PRIVATE);
        
        // Install presets in view
        editNick = (EditText)findViewById(R.id.editNick);
        editPass = (EditText)findViewById(R.id.editPass);
        chkSecure = (CheckBox)findViewById(R.id.chkSecure);
        chkRemember = (CheckBox)findViewById(R.id.chkRemember);
        chkInvis = (CheckBox)findViewById(R.id.chkInvis);
        
        chkRemember.setChecked(settings.getBoolean("remember", false));
        if(chkRemember.isChecked()) {
	        editNick.setText(settings.getString("nickname", ""));
	        editPass.setText(settings.getString("password", ""));
        }
        
        chkSecure.setChecked(settings.getBoolean("secure", false));
        chkInvis.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				editNick.setEnabled(!isChecked);
				editPass.setEnabled(!isChecked);
				chkSecure.setEnabled(!isChecked);
				chkRemember.setEnabled(!isChecked);
			}
		});
        chkInvis.setChecked(settings.getBoolean("invis", false));
        
        btnConnect = (Button)findViewById(R.id.btnConnect);
        btnConnect.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				http.setSecure(chkSecure.isChecked());
				Connector connector = new Connector();
				connector.setConnectString(res.getString(R.string.connecting));
				connector.execute(editNick.getText().toString(), editPass.getText().toString());	
			}
		});
        
        btnCancel = (Button)findViewById(R.id.btnCancel);
        btnCancel.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				setResult(RESULT_CANCELED);
				finish();
			}
		});
        
        // debug
        chkInvis.setEnabled(false);
        chkSecure.setEnabled(false);
    }
    
    private void processConnectorResult() {
    	if(connectorStatus == RStatus.CONNECTED) {
			saveLoginCreds();
			setResult(RESULT_OK);
			finish();
		}
		else {
			if(connectorStatus == RStatus.WRONG_USERPASS)
				popAlert(res.getString(R.string.connect_unable), res.getString(R.string.connect_wrong));
			else
				popAlert(res.getString(R.string.connect_unable), res.getString(R.string.connect_unexpected) + " | " + connectorStatus);
		}
    }
    
    private void popAlert(String title, String text) {
    	final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
    	alertDialog.setTitle(title);
    	alertDialog.setMessage(text);
    	alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
    	   public void onClick(DialogInterface dialog, int which) {
    	      alertDialog.dismiss();
    	   }
    	});
    	alertDialog.show();
    }
    
    public void saveLoginCreds() {
    	SharedPreferences.Editor editor = settings.edit();
    	editor.putString("nickname", editNick.getText().toString());
    	editor.putString("password", editPass.getText().toString());
    	editor.putBoolean("secure", chkSecure.isChecked());
    	editor.putBoolean("invis", chkInvis.isChecked());
    	editor.putBoolean("remember", chkRemember.isChecked());
    	
    	editor.putString("cookie", http.getCookie());
    	
    	editor.commit();
    }
    
    public class Connector extends AsyncTask<String, Boolean, RStatus> {
		String connecting;
		ProgressDialog connectingDialog;
		
		public void setConnectString(String connecting) {
			this.connecting = connecting;
		}
		
		@Override
		protected void onPreExecute() {
			connectingDialog = ProgressDialog.show(ConnectorActivity.this, "", connecting, true, false);
		}
		
		@Override
		protected RStatus doInBackground(String... params) {
			if(http == null)
				return RStatus.NO_HTTP;
			
			if(!http.isReady())
				return RStatus.NOT_READY;
			
			//http.setAvoidRedirect(false);
			//HttpData data = http.sendPost("/?section=LOGIN", new String[][] {{"username", params[0]}, {"password",  params[1]}, {"secure_login", ""}});
			HttpData data = http.connect(params[0], params[1]);
			
			String redirUrl = null;
			if(data.getStatus() == RStatus.REDIRECT)
				redirUrl = data.getRedirect();
			else if(data.getStatus() == RStatus.ENDED)
				return RStatus.WRONG_USERPASS;
			else return data.getStatus();
			
			if(redirUrl.equals("/?section=INDEX")) {
				http.setConnected(true);
				return RStatus.CONNECTED;
			}
			
			return RStatus.ERROR;
		}
		
		@Override
		protected void onPostExecute(RStatus result) {
			connectorStatus = result;
			connectingDialog.dismiss();
			processConnectorResult();
		}
	}
}
